<template>
  <div class="common-container">
    <div class="header">
      <div class="header_left">
        <el-input v-model="search_val" placeholder="请输入安装点名称" clearable @clear="clearNickname" size="small"
          style="width: 220px;margin-right: 15px;">
          <el-button slot="append" :icon="loadingSearch ? 'el-icon-loading' : 'el-icon-search'" @click="searchClick">
          </el-button>
        </el-input>

        <el-popover placement="bottom" width="460" trigger="click" popper-class="popover" size="small"
          v-model="showPopover">
          <div>
            <el-form label-width="70px" style="margin: 20px 0" class="popover_from">

              <el-form-item size="small" label="建筑物">
                <el-select size="small" style="width: 360px;margin-left: 15px;" clearable @change="projectchange2"
                  v-loadMore="loadMore2" v-model='buildingsName' @visible-change="buildingsChange" placeholder='请选择建筑物'
                  filterable remote :remote-method="remoteMethod2" @clear="clearBuildings">
                  <el-option v-for='item in buildings' :label='item.name' :value='item.id' :key='item.id'>
                  </el-option>
                  <div class="div_box" v-loading="loading2" :style="loading2 ? '' : 'display: none;'"> </div>
                </el-select>
              </el-form-item>

              <el-form-item size="small" label="楼层">
                <el-select size="small" style="width: 360px;margin-left: 15px;" clearable @change="projectchange3"
                  v-loadMore="loadMore3" v-model='floorName' placeholder='请选择楼层' filterable remote
                  :remote-method="remoteMethod3" @clear="handleClear3">
                  <el-option v-for='item in floor' :label='item.name' :value='item.id' :key='item.id'>
                  </el-option>
                  <div class="div_box" v-loading="loading3" :style="loading3 ? '' : 'display: none;'"> </div>
                </el-select>
              </el-form-item>

              <el-form-item size="small" label="布防状态">
                <el-select v-model="searchForm.isDefence" filterable placeholder="请选择布防状态"
                  style="width: 360px;margin-left: 15px;" size="small" clearable >
                  <el-option v-for="(item, i) in isDefenceList" :key="i" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>

            </el-form>
            <div class="footer" style="text-align: right">
              <el-button size="small" @click="resetClick" class="cancel-button">重 置</el-button>
              <el-button size="small" class="confirm-button" @click="onSearch">确 定</el-button>
            </div>
          </div>
          <el-button size="small" slot="reference" :class="hasSearch ? 'elhasSearch elhasSearch2' : 'elhasSearch2'">
            高级搜索<i class="el-icon-search" style="margin-left: 5px; font-size: 12px"></i></el-button>
        </el-popover>

      </div>
      <div class="header_right">
        <el-button size="small" style="margin-left: 15px;" icon="el-icon-plus" @click="onAdd"
          v-if="orgInfo.orgId">新增</el-button>
        <el-button size="small" class="el_button" @click="importClick" icon="el-icon-download">导入</el-button>
        <el-dropdown @command="onDropdown">
          <el-button size="small" style="margin-left: 15px;">
            批量操作<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <!-- <el-dropdown-item command="batch">批量操作</el-dropdown-item> -->
            <el-dropdown-item command="set">一键布防</el-dropdown-item>
            <el-dropdown-item command="remove">一键撤防</el-dropdown-item>
            <el-dropdown-item command="del">批量删除</el-dropdown-item>
            <el-dropdown-item command="alarmReceiver">设置接警人</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    <div class="content">
      <el-table :data="tableData" height="calc(100% - 65px)" class="table" @selection-change="batchSelect"
        :header-cell-style="headerStyle" row-key="id" ref="refMultipleTable" v-loading="loadingTable"
        element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(47, 51, 73, 0.3)">
        <el-table-column align="center" type="selection" :reserve-selection="true" min-width="40">
        </el-table-column>
        <el-table-column align="center" label="序号" type="index" width="50">
        </el-table-column>
        <el-table-column align="center" prop="name" label="安装点" show-overflow-tooltip>
        </el-table-column>
        <el-table-column align="center" prop="orgName" label="联网单位" show-overflow-tooltip>
        </el-table-column>
        <el-table-column align="center" prop="buildingName" label="建筑物" show-overflow-tooltip>
        </el-table-column>
        <el-table-column align="center" prop="floorName" label="楼层" show-overflow-tooltip>
        </el-table-column>
        <el-table-column align="center" prop="isDefence" label="布防状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.isDefence == 0" type="warning">已撤防</el-tag>
            <el-tag v-else type="success">已布防</el-tag>
          </template>
        </el-table-column>

        <!-- <el-table-column align="center" prop="address" label="地址" min-width="120" show-overflow-tooltip>
              <template slot-scope="scope">
                {{scope.row.province}}{{scope.row.city}}{{scope.row.area}}{{scope.row.address}}
              </template>
            </el-table-column> -->
        <el-table-column align="center" prop="deviceCount" label="管理设备数">
        </el-table-column>

        <el-table-column align="center" prop="management" label="操作" width="200" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="布防" placement="bottom">
              <i @click="onSet(scope.row)" class="iconfont anquan1 tableBtnIcon"></i>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="撤防" placement="bottom">
              <i @click="onRemove(scope.row)" class="iconfont iconfontquxiaoshouquan tableBtnIcon"></i>
            </el-tooltip>
            <!-- <el-tooltip class="item" effect="dark" content="编辑" placement="bottom">
                  <i @click="onEdit(scope.row)" class="iconfont tianxie tableBtnIcon"></i>
                </el-tooltip> -->
            <el-tooltip class="item" effect="dark" content="详情" placement="bottom">
              <i @click="onDetails(scope.row)" class="iconfont xiangqing tableBtnIcon"></i>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="bottom">
              <i @click="onDel(scope.row.id)" class="iconfont shanchu tableBtnIcon"></i>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination :total="total" :page.sync="page" :limit.sync="limit" @pagination="getreqParkList"
        class="pagination" />
    </div>
    <addModel ref="refAdd" :orgInfo="orgInfo"></addModel>
    <editModel ref="refEdit" :getLocationInfo="getLocationInfo"></editModel>
    <batchModel ref="refBatch"></batchModel>
    <alarmReceiver ref="refAlarmReceiver" :batchDate='batchDate' :orgInfo="orgInfo"></alarmReceiver>
    <import-device ref="refImportDevice" :getAddressflag="getAddressflag"
      :getLocationInfo="getLocationInfo"></import-device>
  </div>
</template>

<script>
import addModel from "./components/addModel.vue";
import editModel from "./components/editModel.vue";
import batchModel from "./components/batchModel.vue";
import alarmReceiver from "./components/alarmReceiver.vue";
import tableStyleMixin from "@mixin/table-style";
import Pagination from "@components/Pagination.vue";
import {
  reqSpaceManager,
  reqDel,
  reqBatchDefence,
  reqBatchDel,
} from "@/api/api";
import { mapState, mapMutations } from "vuex";
import advanceSearchMixin from "./mixins/advanceSearch.js";
import TreeSelSearch from "@components/TreeSelSearch.vue";
import loadMore from "@mixin/loadMore";
import ImportDevice from "./components/ImportDevice.vue"; //导入组件

export default {
  props: ['orgInfo'],
  name: "org-list",
  components: {
    Pagination,
    addModel,
    editModel,
    batchModel,
    alarmReceiver,
    TreeSelSearch,
    ImportDevice
  },
  mixins: [tableStyleMixin, advanceSearchMixin, loadMore],
  data() {
    return {
      searchForm: {
        parentId: "",
        spaceId: "", //楼层
      },
      parentId: "",
      loadingSearch: false, //查询按钮loading
      // parkList: [],
      search_val: "",
      page: 1,
      limit: 10,
      total: 100,
      tableData: [],
      loadingTable: false,
      getLocationInfo: {
        getLat: "",
        getLng: "",
        getAdd: "",
        province: "",
        city: "",
        area: "",
        provinceCityAreaValue: "",
      },
      isDefenceList: [
        {
          name: '已撤防',
          id: '0'
        }, {
          name: '已布防',
          id: '1'
        }
      ],
      batchDate: [],
      floor: [],
    };
  },
  mounted() {
  },
  computed: {
    ...mapState(["user"]),
  },
  methods: {
    ...mapMutations(["selectMenu"]),
    // 单位id
    changeOrgId(val) {
      this.searchForm.orgId = val;
    },

    // 清空
    clearNickname() {
      this.page = 1;
      this.limit = 10;
      // 如果只选了建筑物就是建筑物的id,选了楼层就是传楼层的id
      if (this.searchForm.spaceId != null && this.searchForm.spaceId != "") {
        // console.log(2222222);
        this.parentId = this.searchForm.spaceId;
      } else {
        this.parentId = this.searchForm.parentId;
      }
      this.getreqParkList();
    },
    //查询
    async searchClick() {
      this.page = 1;
      this.limit = 10;
      this.loadingSearch = true;
      await this.getreqParkList();
      this.loadingSearch = false;
    },
    // 选择复选框批量
    batchSelect(arr) {
      this.batchDate = [];
      arr.forEach((c) => {
        this.batchDate.push(c.id);
      });
      // console.log(this.batchDate);
    },
    // 更多操作回调事件
    onDropdown(e) {
      if (this.batchDate.length <= 0) {
        this.$modal.notifyWarning("请勾选要操作的安装点");
        return;
      }
      switch (e) {
        case "batch":
          // console.log("batch");
          this.$refs.refBatch.dialogVisible = true;
          break;

        case "set":
          this.$confirm(
            "一键布防将对该安装点进行布防，确认后将更新该安装点下所有设备为布防状态",
            "安装点批量布防",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(async () => {
              const res = await reqBatchDefence({
                spaceIdList: this.batchDate,
                isDefence: "1",
              });
              if (res.code !== 20000)
                return this.$modal.notifyWarning(res.message);
              this.$modal.notifySuccess("批量设置布防成功!");
              this.getreqParkList();
              this.clearSelections(); //清空复选框
            })
            .catch(() => { });
          break;

        case "remove":
          this.$confirm(
            "一键撤防将对该安装点进行撤防，确认后将更新该安装点下所有设备为撤防状态",
            "安装点批量撤防",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(async () => {
              const res = await reqBatchDefence({
                spaceIdList: this.batchDate,
                isDefence: "0",
              });
              if (res.code !== 20000)
                return this.$modal.notifyWarning(res.message);
              this.$modal.notifySuccess("批量设置撤防成功!");
              this.getreqParkList();
              this.clearSelections(); //清空复选框
            })
            .catch(() => { });
          break;

        case "alarmReceiver":
          // if(!this.orgId) return this.$modal.notifyWarning('请先选择单位');
          this.$refs.refAlarmReceiver.dialogVisible = true;
          this.$refs.refAlarmReceiver.getDataList();
          break;

        case "del":
          // console.log("del");
          this.$confirm("此操作将批量删除安装点, 是否继续?", "批量删除", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(async () => {
              const res = await reqBatchDel({
                spaceIdList: this.batchDate,
                userId: this.user.userId
              });
              if (res.code !== 20000)
                return this.$modal.notifyWarning(res.message);
              this.$modal.notifySuccess("批量删除安装点成功!");
              this.getreqParkList();
              this.clearSelections(); //清空复选框
            })
            .catch(() => { });
          break;
      }
    },
    // 清空复选框√√
    clearSelections() {
      this.$refs.refMultipleTable.clearSelection();
    },
    // 新增
    onAdd() {
      this.$refs.refAdd.getbuildings();
      this.$refs.refAdd.dialogVisible = true;
    },
    onSet(row) {
      // 布防
      this.$confirm("确定布防该安装点?", "布防", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // row.isDefence = 1;
          const res = await reqBatchDefence({
            spaceIdList: [row.id],
            isDefence: "1",
          });
          // const res = await reqUpdate(row);
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.$modal.notifySuccess("布防成功!");
          this.getreqParkList();
        })
        .catch(() => { });
    },
    onRemove(row) {
      // 撤防
      this.$confirm("确定撤防该安装点?", "撤防", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // row.isDefence = 0;
          const res = await reqBatchDefence({
            spaceIdList: [row.id],
            isDefence: "0",
          });
          // const res = await reqUpdate(row);
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.$modal.notifySuccess("撤防成功!");
          this.getreqParkList();
        })
        .catch(() => { });
    },
    // 去到详情
    onDetails(row) {
      this.$store.commit("saveSpInfo", row); //保存安装点信息，使页面刷新信息还存在
      this.$router.push("/mountPointsDefine/list");
      this.selectMenu({
        name: "安装点详情",
        url: `/mountPointsDefine/list`,
        value: "mountPointsDefine",
      });
    },
    onEdit(item) {
      // console.log(item, "item");
      this.getLocationInfo = item;
      this.$refs.refEdit.dialogVisible = true;
    },
    onDel(id) {
      this.$confirm("此操作将永久删除该安装点, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await reqDel({
            id,
            userId: this.user.userId
          });
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.$modal.notifySuccess("删除安装点成功");
          this.getreqParkList();
        })
        .catch(() => { });
    },

    // 空间列表
    async getreqParkList(id, Flag) {
      this.loadingTable = true;
      let res = await reqSpaceManager(this.page, this.limit, {
        userId: this.user.userId,
        roleName: this.user.roleName,
        name: this.search_val,
        orgId: this.orgInfo.orgId,
        isDefence: this.searchForm.isDefence,
        parentId: Flag ? id : this.parentId, // 如果只选了建筑物就是建筑物的id,选了楼层就是传楼层的id
        metaCode: 3,
        isStatistics: 1
      });
      this.loadingTable = false;
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.hasSearch = (this.parentId || this.searchForm.isDefence) ? true : false
      this.tableData = res.data.rows;
      this.total = res.data.total;
    },
    // 楼层点击安装点数量
    getSpaces(e) {
      // 清空建筑物
      this.buildingsName = '';
      this.buildingsName2 = '';
      this.sysInstanceIndex2 = 1;
      this.sysInstanceTotalPages2 = 10;
      this.buildings = []

      this.floor = [{ id: e.name, name: e.name }]
      this.floorName = e.name;
      this.searchForm.spaceId = e.id;
      this.parentId = e.id;
      this.getreqParkList();
    },
    // 建筑物点击安装点数量
    getMounting(e) {
      this.flag = false;
      this.buildings = [{ id: e.name, name: e.name }]
      this.buildingsName = e.name
      this.searchForm.parentId = e.id;
      this.searchForm.spaceId = ''
      this.handleClear3()
      // this.searchClick1();
    },
  },
  async created() {
  },
};
</script>

<style scoped lang="less">
@import url("~@views/style/tablePage.less");

::v-deep .el-button--small {
  background: #7367f0;
  color: #fff;
  border: none;
}

// .el-button {
//   line-height: 0;
// }

// 下拉框加载开始
.div_box {
  height: 276px;
  position: absolute;
  top: -1px;
  left: -1px;
  width: 100%;
  z-index: 9999;
}

::v-deep .el-loading-mask {
  border-radius: 4px;
}

// 下拉框加载结束

// 高级搜索
::v-deep .el-button--primary {
  background-color: #7367f0;
  border: 1px solid #7367f0;
  color: #fff;
}

::v-deep .el-form-item__label {
  color: @primaryThemeTxtColor2 ;
  padding: 0px;
}

::v-deep .el-input__inner {
  color: var(--primaryContentTxt, #f1f1f1);
}

.dropdown {
  background: #7367f0;
  color: #fff;
  border: none;
}

// 高级搜索----------</style>